<template>
  <div class="farm-detail">
    <el-container>
      <el-header>
        <div class="header-content">
          <div class="header-left">
            <el-button type="primary" @click="router.back()">
              <el-icon><ArrowLeft /></el-icon>
              返回
            </el-button>
            <el-button 
              v-if="farmDetail?.farmInfo?.statusId === 2" 
              type="success" 
              @click="router.push(`/farm/products/${route.params.farmId}`)"
            >
              <el-icon><ShoppingCart /></el-icon>
              查看商品
            </el-button>
          </div>
          <div class="header-center">
            <img src="https://susu-plants.oss-cn-beijing.aliyuncs.com/2025-03-04-22-13-33QQ20250304-190757.png" alt="Logo" class="logo-image">
            <h2>农场详情</h2>
          </div>
        </div>
      </el-header>
      <el-main>
        <div v-if="farmDetail" class="detail-content">
          <!-- 图片展示卡片 -->
          <el-card class="images-card">
            <template #header>
              <div class="card-header">
                <h3>农场图片</h3>
              </div>
            </template>
            <div class="images-content">
              <el-carousel v-if="farmDetail.images && farmDetail.images.length > 0" 
                :interval="4000" 
                height="300px"
                :autoplay="false"
                indicator-position="outside">
                <el-carousel-item v-for="(url, index) in farmDetail.images" :key="index">
                  <el-image
                    :src="url"
                    fit="contain"
                    style="height: 300px;"
                    :preview-src-list="farmDetail.images"
                    :initial-index="index"
                  />
                </el-carousel-item>
              </el-carousel>
              <div v-else class="no-images">
                暂无图片
              </div>
            </div>
          </el-card>

          <!-- 基本信息卡片 -->
          <el-card class="info-card">
            <template #header>
              <div class="card-header">
                <h3>基本信息</h3>
              </div>
            </template>
            <div class="info-content">
              <div class="info-item">
                <span class="label">农场名称：</span>
                <span class="value">{{ farmDetail.farmInfo.farmName }}</span>
              </div>
              <div class="info-item">
                <span class="label">农场地址：</span>
                <span class="value">{{ farmDetail.farmInfo.farmAddress }}</span>
              </div>
              <div class="info-item">
                <span class="label">农场描述：</span>
                <span class="value">{{ farmDetail.farmInfo.farmDescription || '暂无描述' }}</span>
              </div>
              <div class="info-item">
                <span class="label">申请补贴：</span>
                <span class="value">¥{{ farmDetail.farmInfo.appliedSubsidyAmount }}</span>
              </div>
              <div class="info-item">
                <span class="label">创建时间：</span>
                <span class="value">{{ formatDate(farmDetail.farmInfo.createdAt) }}</span>
              </div>
              <div class="info-item">
                <span class="label">当前状态：</span>
                <el-tag :type="getStatusType(farmDetail.farmInfo.statusId)">
                  {{ getStatusText(farmDetail.farmInfo.statusId) }}
                </el-tag>
              </div>
              <!-- 添加操作按钮区域 -->
              <div class="action-buttons" v-if="currentUserId === farmDetail.farmInfo.userId">
                <el-button 
                  type="primary" 
                  v-if="farmDetail.farmInfo.statusId === 3 || farmDetail.farmInfo.statusId === 0"
                  @click="handleReapply"
                >
                  重新提交申请
                </el-button>
                <el-button 
                  type="warning" 
                  v-if="farmDetail.farmInfo.statusId === 0 || farmDetail.farmInfo.statusId === 2 || farmDetail.farmInfo.statusId === 3"
                  @click="handleEdit"
                >
                  修改农场信息
                </el-button>
              </div>
            </div>
          </el-card>
        </div>
        <div v-else class="loading">
          <el-empty description="加载中..." v-if="loading" />
          <el-empty description="暂无数据" v-else />
        </div>
      </el-main>
    </el-container>

    <!-- 添加修改信息对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="修改农场信息"
      width="60%"
      :before-close="handleCloseDialog"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editRules"
        label-width="100px"
      >
        <el-form-item label="农场名称">
          <el-input v-model="editForm.farmName" disabled />
        </el-form-item>

        <el-form-item label="农场地址" prop="farmAddress">
          <el-input v-model="editForm.farmAddress" placeholder="请输入农场地址" />
        </el-form-item>

        <el-form-item label="农场描述" prop="farmDescription">
          <el-input
            type="textarea"
            v-model="editForm.farmDescription"
            :rows="3"
            placeholder="请输入农场描述"
          />
        </el-form-item>

        <el-form-item label="农场图片">
          <div class="image-list">
            <div v-for="(url, index) in farmDetail.images" :key="index" class="image-item">
              <el-image :src="url" fit="cover" class="preview-image" />
              <div class="image-actions">
                <el-button
                  type="danger"
                  size="small"
                  circle
                  @click="handleDeleteImage(url)"
                >
                  <el-icon><Delete /></el-icon>
                </el-button>
              </div>
            </div>
          </div>
          <el-upload
            class="image-uploader"
            :auto-upload="false"
            :show-file-list="true"
            :limit="5"
            accept="image/*"
            :on-change="handleImageChange"
            multiple
          >
            <template #trigger>
              <el-button type="primary">添加图片</el-button>
            </template>
            <template #tip>
              <div class="el-upload__tip">
                只能上传 jpg/png 文件，且不超过 5MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCloseDialog">取消</el-button>
          <el-button type="primary" @click="handleSubmitEdit">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowLeft, Delete, ShoppingCart } from '@element-plus/icons-vue'
import { getFarmDetail, reapplyFarm, updateFarm } from '@/api/farms'

const router = useRouter()
const route = useRoute()
const farmDetail = ref(null)
const loading = ref(true)
const currentUserId = ref(null)

// 获取当前用户ID
const getCurrentUserId = () => {
  // 从 session 中获取用户ID
  const sessionUserId = sessionStorage.getItem('userId')
  currentUserId.value = sessionUserId ? parseInt(sessionUserId) : null
  console.log('用户权限判断:', {
    sessionUserId: currentUserId.value,
    farmOwnerId: farmDetail.value?.farmInfo?.userId,
    isFarmOwner: currentUserId.value === farmDetail.value?.farmInfo?.userId
  })
}

// 重新提交申请
const handleReapply = async () => {
  try {
    await reapplyFarm(farmDetail.value.farmInfo.farmId, currentUserId.value)
    ElMessage.success('重新提交申请成功')
    // 重新加载农场详情
    await loadFarmDetail()
  } catch (error) {
    console.error('重新提交申请失败:', error)
    ElMessage.error(error?.message || '重新提交申请失败，请稍后重试')
  }
}

// 修改表单相关
const editDialogVisible = ref(false)
const editFormRef = ref(null)
const editForm = ref({
  farmName: '',
  farmAddress: '',
  farmDescription: '',
  newImages: [],
  deletedImageUrls: []
})

const editRules = {
  farmAddress: [
    { required: true, message: '请输入农场地址', trigger: 'blur' }
  ],
  farmDescription: [
    { required: true, message: '请输入农场描述', trigger: 'blur' },
    { min: 2, max: 500, message: '描述长度在 2 到 500 个字符', trigger: 'blur' }
  ]
}

// 打开修改对话框
const handleEdit = () => {
  editForm.value = {
    farmName: farmDetail.value.farmInfo.farmName,  // 仅用于显示
    farmAddress: farmDetail.value.farmInfo.farmAddress,
    farmDescription: farmDetail.value.farmInfo.farmDescription,
    newImages: [],
    deletedImageUrls: []
  }
  editDialogVisible.value = true
}

// 关闭对话框
const handleCloseDialog = () => {
  editDialogVisible.value = false
  editForm.value.newImages = []
  editForm.value.deletedImageUrls = []
  if (editFormRef.value) {
    editFormRef.value.resetFields()
  }
}

// 处理图片选择
const handleImageChange = (file) => {
  const isImage = file.raw.type.startsWith('image/')
  const isLt5M = file.raw.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!')
    return false
  }

  editForm.value.newImages.push(file.raw)
}

// 处理删除图片
const handleDeleteImage = async (url) => {
  try {
    await ElMessageBox.confirm('确定要删除这张图片吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    editForm.value.deletedImageUrls.push(url)
  } catch {
    // 用户取消删除
  }
}

// 提交修改
const handleSubmitEdit = async () => {
  if (!editFormRef.value) return

  try {
    await editFormRef.value.validate()
    
    const formData = new FormData()
    formData.append('farmAddress', editForm.value.farmAddress)
    formData.append('farmDescription', editForm.value.farmDescription)
    
    // 添加新图片
    editForm.value.newImages.forEach(image => {
      formData.append('newImages', image)
    })
    
    // 添加要删除的图片URL
    editForm.value.deletedImageUrls.forEach(url => {
      formData.append('deletedImageUrls', url)
    })

    try {
      await updateFarm(farmDetail.value.farmInfo.farmId, formData)
      // 如果没有抛出错误，说明更新成功
      ElMessage.success('更新成功')
      editDialogVisible.value = false
      await loadFarmDetail() // 重新加载农场详情
    } catch (error) {
      console.error('API调用错误:', error)
      ElMessage.error(error?.response?.data?.message || '更新失败，请稍后重试')
    }
  } catch (validationError) {
    console.error('表单验证错误:', validationError)
    ElMessage.error('请检查表单填写是否正确')
  }
}

// 格式化日期
const formatDate = (dateString) => {
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 获取状态类型
const getStatusType = (statusId) => {
  switch (statusId) {
    case 1:
      return 'warning'  // 申请中
    case 3:
      return 'danger'   // 已拒绝
    case 0:
      return 'primary'  // 创办中
    case 2:
      return 'success'  // 营业中
    default:
      return 'info'
  }
}

// 获取状态文本
const getStatusText = (statusId) => {
  switch (statusId) {
    case 1:
      return '申请中'
    case 3:
      return '已拒绝'
    case 0:
      return '创办中'
    case 2:
      return '营业中'
    default:
      return '未知状态'
  }
}

// 加载农场详情
const loadFarmDetail = async () => {
  try {
    loading.value = true
    const farmId = route.params.farmId
    const userId = route.query.userId
    
    console.log('Loading farm details:', { farmId, userId })
    
    if (!farmId || !userId) {
      throw new Error('缺少必要参数')
    }
    
    const res = await getFarmDetail(farmId, userId)
    console.log('API Response:', res)
    
    // 检查响应数据是否包含必要的信息
    if (res && res.farmInfo && res.images) {
      farmDetail.value = res
      console.log('Farm details loaded:', farmDetail.value)
      // 在数据加载完成后重新检查权限
      getCurrentUserId()
    } else {
      throw new Error('获取农场详情失败：数据格式不正确')
    }
  } catch (error) {
    console.error('加载农场详情失败:', error)
    ElMessage.error(error.message || '加载农场详情失败，请重试')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  getCurrentUserId()
  loadFarmDetail()
})
</script>

<style scoped>
.farm-detail {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.el-header {
  padding: 0;
  background-color: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
  padding: 0 20px;
}

.header-left {
  flex: 0 0 auto;
}

.header-center {
  flex: 1;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
}

.logo-image {
  height: 40px;
  width: auto;
}

.header-center h2 {
  margin: 0;
  color: #409EFF;
}

.el-main {
  padding: 20px;
  margin: 80px auto 0;
  max-width: 80%;
  margin: 0 auto;
}

.detail-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.images-card {
  width: 100%;
}

.images-content {
  min-height: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f8f9fa;
  width: 600px;
  margin: 0 auto;
}

.el-carousel {
  width: 600px;
}

.el-carousel :deep(.el-carousel__container) {
  height: 300px !important;
}

.el-carousel :deep(.el-carousel__indicators) {
  bottom: -25px;
}

.el-carousel :deep(.el-carousel__indicators--outside) {
  position: relative;
  margin-top: 8px;
}

.el-carousel__item {
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f8f9fa;
}

.el-image {
  max-width: 100%;
  max-height: 300px;
  object-fit: contain;
}

.info-card {
  width: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 10px;
}

.card-header h3 {
  margin: 0;
  font-size: 18px;
  color: #303133;
}

.info-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
  padding: 20px 0;
}

.info-item {
  display: flex;
  align-items: center;
  font-size: 14px;
  line-height: 1.8;
}

.info-item .label {
  width: 100px;
  color: #606266;
  font-weight: 500;
}

.info-item .value {
  color: #303133;
  flex: 1;
}

.no-images {
  height: 300px;
  width: 600px;
  margin: 0 auto;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #909399;
  font-size: 14px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.loading {
  height: 300px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.action-buttons {
  margin-top: 20px;
  display: flex;
  gap: 10px;
  justify-content: flex-end;
  padding-top: 20px;
  border-top: 1px solid #EBEEF5;
}

@media (max-width: 768px) {
  .el-carousel :deep(.el-carousel__container) {
    height: 250px !important;
  }
  
  .images-content,
  .no-images {
    min-height: 250px;
    width: 100%;  /* 在小屏幕上使用全宽 */
  }
  
  .el-carousel {
    width: 100%;  /* 在小屏幕上使用全宽 */
  }
  
  .el-image {
    max-height: 250px;
  }
}

.image-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 20px;
}

.image-item {
  position: relative;
  width: 150px;
  height: 150px;
  border-radius: 4px;
  overflow: hidden;
}

.preview-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.image-actions {
  position: absolute;
  top: 5px;
  right: 5px;
  display: flex;
  gap: 5px;
}

.image-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  padding: 20px;
  text-align: center;
}

.image-uploader:hover {
  border-color: #409EFF;
}

.dialog-footer {
  padding-top: 20px;
  text-align: right;
}
</style>